<template>
	<el-upload class="avatar-uploader" :action="requestPath" :on-success="handleAvatarSuccess"
		:before-upload="beforeAvatarUpload">
		<img v-if="imageUrl" :src="imageUrl" class="avatar" />
		<el-icon v-else class="avatar-uploader-icon">
			<Plus />
		</el-icon>
	</el-upload>
</template>

<script setup lang="ts">
import { ElMessage, type UploadProps } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import { ref } from 'vue';
const props = defineProps<{
	emitFunc: Function,
	avatar?: string
}>()
const requestPath = '/api/file/upload'
const imageUrl = ref(props.avatar)
console.log(props.avatar);

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
	console.log(response);
	props.emitFunc(response.data)
	imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('上传文件只能为JPG格式！')
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('上传文件大小必须小于2MB！')
		return false
	}
	return true
}
</script>

<style lang="less" scoped>
.avatar-uploader {
	.avatar {
		width: 100px;
		height: 100px;
		display: block;
	}
}
</style>

<style lang="less">
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 100px;
	height: 100px;
	text-align: center;
}
</style>